/**
 * 获取文件内容
 */
void httpGetFile(clientRequestTask *t)
{
    sprintf(t->path, "%s%s", t->xp->path, t->uri);
    if (t->path[strlen(t->path) - 1] == '/') {
        strcat(t->path, "index.html");
    }

    int find = 1;
    struct stat st;

    if (stat(t->path, &st) == -1) {
        find = 0;
    } else {
        if ((st.st_mode & S_IFMT) == S_IFDIR) {
            strcat(t->path, "/index.html");
            if (stat(t->path, &st) == -1) {
                find = 0;
            }
        }
        if ((st.st_mode & S_IFMT) != S_IFREG) {
            find = 0;
        }
    }

    FILE* resource;
    if (find) {
        resource = fopen(t->path, "r");
        if (resource == NULL) {
            find = 0;
        }
    }

    if (find) {

        char *ext = strrchr(t->path, '.'); /* extension */
        char *ct = getMimesConfig(ext ? ext + 1 : "html");

        httpResponse(t, 200, NULL, ct, st.st_size);

        if (t->lw > 0) {
            int sfd = fileno(resource);
            int result;
            for (;;) {
                result = sendfile(t->fd, sfd, NULL, 512);
                if (result == 0)
                    break;
                else if (result == -1) {
                    if (errno == EAGAIN && t->exit == 0) {
                        sem_wait(&(t->sem));
                        continue;
                    }
                }
            }
        }

        fclose(resource);

    } else {
        httpResponse(t, 404, NULL, NULL, 0);
    }
}

/**
 * 获取文件上传进度
 * 1、post 上传文件，假设文件 uri 为 /xerw2xee27
 * 2、在 get 请求上传进度时，添加 querystring 设定: ?action=progress   
 *    返回 json 格式的上传进度:
 *    { 'status' : 'ok', 'read': 377, 'total': 28777 }
 */
void httpGetProgess(clientRequestTask *t)
{
    char* key = t->uri;
    char* mime = getMimesConfig("json");
    const char* tpl = "{ \"status\" : \"%s\", \"read\" : %d, \"total\" : %d }\n";

    extern clientRequestTask* task;
    clientRequestTask *up = task; /* upload task */

    while (up != NULL) {
        if (strcmp(up->uri, key) == 0 && up->contentLength > 0) {
            sprintf(t->line, tpl, "ok", up->lr, up->contentLength);
            break;
        }
        up = up->next;
    }

    if (up == NULL) {
        sprintf(t->line, tpl, "key not found", 0, 0);  
    }
    
    httpResponse(t, 200, t->line, mime, strlen(t->line));
}

/**
 * GET 方法
 */
void httpGet(clientRequestTask *t)
{
    char* progress = "action=progress";
    if (strncmp(t->query, progress, strlen(progress)) == 0) {
        httpGetProgess(t);
    } else {
        httpGetFile(t);
    }
}

